// DynamicController.java

package com.huhao.wshare.controller;

import com.huhao.wshare.dto.Dynamic.CommentDTO;
import com.huhao.wshare.dto.Dynamic.CommentCreateDTO;
import jakarta.validation.Valid;
import com.huhao.wshare.dto.Dynamic.DynamicCreateDTO;
import com.huhao.wshare.dto.Dynamic.DynamicDTO;
import com.huhao.wshare.service.DynamicService;
import com.huhao.wshare.service.security.CustomUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/dynamics")
@RequiredArgsConstructor
public class DynamicController {

    private final DynamicService dynamicService;

    // ... createDynamic, deleteDynamic, getFriendDynamics 方法保持不变 ...
    @PostMapping
    public ResponseEntity<DynamicDTO> createDynamic(
            @RequestBody DynamicCreateDTO createDTO,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        DynamicDTO dynamic = dynamicService.createDynamic(userId, createDTO);
        return new ResponseEntity<>(dynamic, HttpStatus.CREATED);

    }
    /**
     * 【新增API端点】
     * 功能: 修改一条动态
     * 路径: PUT /api/dynamics/{id}
     * @param id 要修改的动态ID
     * @param updateDTO 新的动态内容
     * @param currentUser 当前登录用户
     * @return 包含 code, message 和 data(修改后的动态) 的JSON响应体
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateDynamic(
            @PathVariable Long id,
            @Valid @RequestBody DynamicCreateDTO updateDTO, // 复用 DynamicCreateDTO
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        DynamicDTO updatedDynamic = dynamicService.updateDynamic(userId, id, updateDTO);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "动态修改成功");
        response.put("data", updatedDynamic);
        return ResponseEntity.ok(response);
    }


    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteDynamic(
            @PathVariable Long id,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        dynamicService.deleteDynamic(userId, id);
        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "动态删除成功！");
        return ResponseEntity.ok(response);
    }

    /**
     * 【已修改响应体】
     * 功能: 分页获取朋友圈动态列表 (核心功能)
     * 路径: GET /api/dynamics/feed
     * @param currentUser Spring Security 自动注入的当前用户信息
     * @param page 页码
     * @param size 每页数量
     * @return 包含 code, message 和分页数据(data)的JSON响应体
     */
    @GetMapping("/feed")
    public ResponseEntity<Map<String, Object>> getFriendDynamics(
            @AuthenticationPrincipal CustomUserDetails currentUser,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Long userId = currentUser.getUser().getId();
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));

        // 1. 调用服务层获取数据
        Page<DynamicDTO> dynamicsPage = dynamicService.getFriendDynamics(userId, pageable);

        // 2. 构建统一的响应体
        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value()); // 200
        response.put("message", "朋友圈动态获取成功");
        response.put("data", dynamicsPage); // 将分页数据放入 data 字段

        // 3. 返回封装后的响应
        return ResponseEntity.ok(response);
    }

    /**
     * 【已修改响应体】
     * 功能: 分页获取指定用户的动态列表
     * 路径: GET /api/dynamics/user/{userId}
     * @param userId 要查询的用户的ID (从URL路径中获取)
     * @param currentUser Spring Security 自动注入的当前用户信息
     * @param page 页码
     * @param size 每页数量
     * @return 包含 code, message 和分页数据(data)的JSON响应体
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserDynamics(
            @PathVariable Long userId,
            @AuthenticationPrincipal CustomUserDetails currentUser,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        Long currentUserId = currentUser.getUser().getId();
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createTime"));

        // 1. 调用服务层获取数据
        Page<DynamicDTO> dynamicsPage = dynamicService.getUserDynamics(userId, currentUserId, pageable);

        // 2. 构建统一的响应体
        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value()); // 200
        response.put("message", "获取指定用户动态成功");
        response.put("data", dynamicsPage); // 将分页数据放入 data 字段

        // 3. 返回封装后的响应
        return ResponseEntity.ok(response);
    }
    /**
     * 【新增】
     * 功能: 点赞一条动态
     * 路径: POST /api/dynamics/{dynamicId}/like
     * @param dynamicId 动态ID
     * @param currentUser 当前登录用户
     * @return 包含 code 和 message 的JSON响应体
     */
    @PostMapping("/{dynamicId}/like")
    public ResponseEntity<Map<String, Object>> likeDynamic(
            @PathVariable Long dynamicId,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        dynamicService.likeDynamic(userId, dynamicId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "点赞成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 【新增】
     * 功能: 取消点赞一条动态
     * 路径: DELETE /api/dynamics/{dynamicId}/like
     * @param dynamicId 动态ID
     * @param currentUser 当前登录用户
     * @return 包含 code 和 message 的JSON响应体
     */
    @DeleteMapping("/{dynamicId}/like")
    public ResponseEntity<Map<String, Object>> unlikeDynamic(
            @PathVariable Long dynamicId,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        dynamicService.unlikeDynamic(userId, dynamicId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "取消点赞成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 【修改点】
     * 功能: 评论一条动态
     * 路径: POST /api/dynamics/{dynamicId}/comment
     * 响应码已从 201 CREATED 修改为 200 OK。
     */
    @PostMapping("/{dynamicId}/comment")
    public ResponseEntity<Map<String, Object>> addComment(
            @PathVariable Long dynamicId,
            @Valid @RequestBody CommentCreateDTO createDTO,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        CommentDTO newComment = dynamicService.addComment(userId, dynamicId, createDTO);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value()); // 修改点: 201 -> 200
        response.put("message", "评论成功");
        response.put("data", newComment);
        return ResponseEntity.ok(response); // 修改点
    }

    /**
     * 【新增API端点】
     * 功能: 修改一条评论
     * 路径: PUT /api/dynamics/comments/{commentId}
     * @param commentId 要修改的评论ID
     * @param updateDTO 新的评论内容
     * @param currentUser 当前登录用户
     * @return 包含 code, message 和 data(修改后的评论) 的JSON响应体
     */
    @PutMapping("/comments/{commentId}")
    public ResponseEntity<Map<String, Object>> updateComment(
            @PathVariable Long commentId,
            @Valid @RequestBody CommentCreateDTO updateDTO,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        CommentDTO updatedComment = dynamicService.updateComment(userId, commentId, updateDTO);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "评论修改成功");
        response.put("data", updatedComment);
        return ResponseEntity.ok(response);
    }

    /**
     * 【新增API端点】
     * 功能: 删除一条评论
     * 路径: DELETE /api/dynamics/comments/{commentId}
     * @param commentId 要删除的评论ID
     * @param currentUser 当前登录用户
     * @return 包含 code 和 message 的JSON响应体
     */
    @DeleteMapping("/comments/{commentId}")
    public ResponseEntity<Map<String, Object>> deleteComment(
            @PathVariable Long commentId,
            @AuthenticationPrincipal CustomUserDetails currentUser
    ) {
        Long userId = currentUser.getUser().getId();
        dynamicService.deleteComment(userId, commentId);

        Map<String, Object> response = new HashMap<>();
        response.put("code", HttpStatus.OK.value());
        response.put("message", "评论删除成功");
        return ResponseEntity.ok(response);
    }
}
